package com.ht.psplan;

import com.ht.aems.communicate.ITransmitPort;
import com.ht.aems.communicate.TcpClientManager;
import com.ht.aems.communicate.TcpPortInfo;
import com.ht.aems.communicate.TcpTransmitPort;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * manager of transmiting voltage plan data to station
 *
 * @author Dong Shufeng
 *         Date: 2007-1-16
 *         Time: 10:49:35
 */
public class PlanTransmitManager {

    private TcpClientManager tcpManager = new TcpClientManager();

    private static PlanTransmitManager instance;

    private PlanTransmitManager() {
    }

    public static PlanTransmitManager getInstance() {
        if (instance == null)
            instance = new PlanTransmitManager();
        return instance;
    }

    public static TcpPortInfo getPortInfo(PlanCommInfo plan) {
        return new TcpPortInfo(plan.getStationAddress(), plan.getPort(), TcpPortInfo.MODE_CLIENT);
    }


    public ITransmitPort getTransmitPort(PlanCommInfo plan) {
        return getTransmitPort(getPortInfo(plan));
    }

    public ITransmitPort getTransmitPort(TcpPortInfo portInfo) {
        if (tcpManager.containsPort(portInfo))
            return tcpManager.getTransPort(portInfo);
        else {
            try {
                Socket socket = new Socket();
                socket.setSoTimeout(10000);
                String ip = portInfo.getRemoteIp().trim();
                int serverPort = portInfo.getServerPort();
                //System.out.println("Connecting to: " + ip);
                socket.connect(new InetSocketAddress(ip, serverPort));
                //socket.connect(new InetSocketAddress("192.168.0.5", 2505));
                TcpTransmitPort port = new TcpTransmitPort(socket);
                port.openPort();
                tcpManager.put(portInfo, port);
                return port;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    public void stopTransports() {
        for (String s : tcpManager.getAllPorts().keySet()) {
            tcpManager.getAllPorts().get(s).stopPort();
        }
    }

    public void stopPort(ITransmitPort port) {
        port.stopPort();
        tcpManager.removePort(port);
    }
}
